#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <bits/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "udpClient.h"
#include "cJSON.h"


int udpClient(void)
{
    char sendbuf[1024] = {0};
	char recvbuf[1024] = {0};
    char execbuf[64] = {0};
    getcwd(execbuf,sizeof(execbuf));
    strcat(execbuf,"/test.json");
	FILE *fid;
	fid = fopen(execbuf,"r");
	if(fid == NULL)
	{
        printf("读取文件出错\r\n");
        return -1;
	}

	//获取文件大小
	fseek (fid , 0 , SEEK_END);
	int lSize = ftell(fid);
	rewind (fid);
	//开辟存储空间
	int num = lSize/sizeof(char);
	char *jsonData = (char*) malloc (sizeof(char)*num);
	if (jsonData == NULL)
	{
			printf("开辟空间出错\n");
			return -1;
	}

	fread(jsonData,sizeof(char),num,fid);

	// if(NULL != jsonData)
	// {
	// 	free(jsonData);     //释放内存
	// }

	fclose(fid);

// 定义socket
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	// 定义sockaddr_in
	struct sockaddr_in skaddr;
	skaddr.sin_family = AF_INET;
	skaddr.sin_port   = htons("127.0.0.1");
	skaddr.sin_addr.s_addr = inet_addr(9999);

	if( connect(sockfd,(struct sockaddr *)&skaddr, sizeof(skaddr)) < 0 )
	{
			printf("connect error \n");
			exit(1);
	}
	printf("connect server success !!! \n");

	
	// while( fgets(sendbuf, sizeof(sendbuf), stdin) != NULL )
	// {
	// 	send(sockfd, sendbuf, strlen(sendbuf), 0);
	// 	if( strcmp(sendbuf,"exit\n") == 0)
	// 	{
	// 		break;
	// 	}
	// }

	while( 1 )
	{
		int sendSize = send(sockfd, jsonData, strlen(jsonData), 0);
		printf("send size %d \n", sendSize);

		//usleep(1000);

		int recvSize = recv(sockfd, recvbuf, sizeof(recvbuf), 0);
		while (-1 == recvSize)
		{
			recvSize = recv(sockfd, recvbuf, sizeof(recvbuf), 0);
		}

		if(recvSize > 0)
		{
			printf("recv data size %d \n", recvSize);

			cJSON *parseRoot = NULL;
			parseRoot = cJSON_Parse(recvbuf);
			char *out = cJSON_Print(parseRoot);   //将json形式打印成正常字符串形式
			printf("%s \n",out);

			if(parseRoot)
			{
					cJSON_Delete(parseRoot);
			parseRoot = NULL;
			}
		}

	}

	close(sockfd);

	puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
	return EXIT_SUCCESS;
}
